/**
 * Copyright(c) 2010 Ceno Techonologies Co., Ltd.
 *
 * History:
 *   15-2-5 上午11:29 Created by piaohhh
 */
package com.jade.bss.beacon.uuid.impl;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.ejb.TransactionAttribute;
import javax.inject.Inject;
import javax.inject.Named;

import com.jade.bss.beacon.BeaconConstants;
import com.jade.bss.beacon.BeaconException;
import com.jade.framework.base.criterion.Criteria;
import com.jade.framework.base.util.PagingList;

import com.jade.bss.beacon.uuid.Uuid;
import com.jade.bss.beacon.uuid.UuidDao;
import com.jade.bss.beacon.uuid.UuidManager;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author <a href="mailto:Administrator@ceno.cn">piaohhh</a>
 * @version 1.0 15-2-5 上午11:29
 */
@Named("jade_beacon_uuidManager")
public class UuidManagerImpl implements UuidManager
{
    private UuidDao uuidDao;

    @Inject
    public void setUuidDao(@Named ("jade_beacon_uuidDao")UuidDao uuidDao)
    {
        this.uuidDao = uuidDao;
    }

    @TransactionAttribute
    @Transactional (rollbackFor = Throwable.class)
    public void add(int count)
    {
        for(int i=0;i<count;i++)
        {
            Uuid uuid =new Uuid();
            uuid.setId(generateUUID());
            uuid.setCreationTime(new Date());
            uuid.setStatus(Uuid.STATUS_AVAILABLE);
            uuidDao.add(uuid);
        }
    }

    @TransactionAttribute
    @Transactional (rollbackFor = Throwable.class)
    public void addManual(String[] ids) throws Exception
    {
        for(String id:ids)
        {
            Uuid uuid = uuidDao.get(id);
            if(uuid !=null)
                throw new BeaconException(BeaconConstants.ERR_BEACON_UUID_EXISTED, "the uuid has already exits", null, id);
            else
                uuid =new Uuid();
                uuid.setId(id);
                uuid.setCreationTime(new Date());
                uuid.setStatus(Uuid.STATUS_AVAILABLE);
                uuidDao.add(uuid);
        }
    }

    @TransactionAttribute
    @Transactional (rollbackFor = Throwable.class)
    public void update(String id, int status)
    {
        uuidDao.update(id,status);
    }

    public Uuid get(String id)
    {
        return uuidDao.get(id);
    }

    public List<Uuid> list(Criteria criteria)
    {
        return uuidDao.list(criteria);
    }

    public PagingList<Uuid> query(Criteria criteria)
    {
        return uuidDao.query(criteria);
    }

    public String generateUUID()
    {
        return UUID.randomUUID().toString();
    }
}
